<template>
	<view class="container">
		<!-- 可滚动内容 -->
		<scroll-view class="scroll-view" scroll-y @scroll="handleScroll" :scroll-top="scrollTop">
			<!-- 用户信息 -->
			<view class="header">
				<view class="user-info">
					<view class="avatar-box">
						<view class="gradient-circle large">
							<image class="avatar-img" :src="activity.avatar" @error="imageError">
							</image>
						</view>
						<view class="upload-sign" @click="followUser"
							v-if="isSelf.isFollowing === false && isSelf.isSelf === false">
							<view>+</view>
						</view>
						<view class="upload-sign" @click="cancel"
							v-if="isSelf.isFollowing === true && isSelf.isSelf === false">
							<view>✓</view>
						</view>
					</view>
					<view class="flex-center">
						<view>
							<view class="name-row">
								<text class="username">{{activity.realName || ''}}</text>
							</view>
							<text class="user-id">ID: {{activity._id || ''}}</text>
						</view>
					</view>
				</view>
				<view class="signature">{{activity.personalIntro || ''}}</view>
				<view class="sign">
					<view class="level-badge">{{activity.age || ''}}</view>
					<view class="level-badge">{{parseChinaAddress(activity.address).province || ''}}</view>
					<view class="flex-center">
						<view class="gender-badge" :style="{'color':activity.gender === '女' ? '#FF8597' : '#00aaff'}">
							{{activity.gender === '女' ? '♀' : '♂'}}
						</view>
					</view>
				</view>
				<!-- 数据面板 -->
				<!-- <view class="data-panel">
					<view class="user-data">
						<view v-for="item in panelData" :key="item.label">
							<view class="user-number">{{ item.value }}</view>
							<view class="user-label">{{ item.label }}</view>
						</view>
					</view>
					<view class="edit-btns">
						<view class="btn">编辑资料</view>
					</view>
				</view> -->
				<!-- <view class="other-panel">
					<view class="other-box" v-for="item in panelOtherData" :key="item.title">
						<view class="other-title">{{ item.title }}</view>
						<view class="other-label">{{ item.label }}</view>
					</view>
				</view> -->
			</view>

			<!-- 内容区域 -->
			<view class="content-section">
				<!-- 标签栏 -->
				<view class="tab-bar">
					<view v-for="(tab, index) in tabs" :key="index" class="tab-item"
						:class="{ active: activeTab === index }" @click="switchTab(index)">
						{{ tab }}
						<view class="indicator gradient-accent" v-if="activeTab === index"></view>
					</view>
				</view>

				<custom-waterfalls-flow :value="DynamicsLists" ref="waterfallsFlowRef" imageKey="coverImage"
					@wapperClick="linkUrl" @imageClick="linkUrl" v-if="activeTab === 0">
					<template v-slot:default="item">
						<view class="item">
							<view class="title">{{item.title}}</view>
							<view class="desc">{{item.describe}}</view>
							<view class="_user">
								<view>
									<u--image :src="activity.avatar" shape="circle" width="20px" height="20px"
										:showLoading="true"></u--image>
									<text>{{activity.realName || ''}}</text>
								</view>
								<view>
									<u-icon name="heart" color="#888" size="22"></u-icon>
									<text>0</text>
								</view>
							</view>
						</view>
					</template>
				</custom-waterfalls-flow>

				<view class="tags_flex" v-if="activeTab === 1">
					<block v-for="(item,index) in activity.tag">
						<u-tag :text="item.tag" type="warning" plain size="large" shape="circle"></u-tag>
					</block>
				</view>

				<!-- <view class="image_flex" v-if="activeTab === 2">
					<block v-for="(item,index) in imgs" :key="index">
						<image :src="item.url" mode="widthFix" @click="checkImage(imgs)"></image>
					</block>
				</view> -->
				<custom-waterfalls-flow :value="imgs" ref="waterfallsFlowRef" imageKey="url" @wapperClick="checkImage"
					@imageClick="checkImage" v-if="activeTab === 2">
				</custom-waterfalls-flow>

				<u-loadmore :status="status" v-if="activeTab === 0" />
			</view>

			<button class="add" @click="reservation" v-if="type !== 'mine'">立即预约</button>
		</scroll-view>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import {
		getSettledUserDetails,
		getUserDynamicsLists,
		followUser,
		isFollow,
		unfollowUser
	} from '../../api/user.js';
	export default {
		data() {
			return {
				panelData: [{
						value: 256,
						label: '关注'
					},
					{
						value: '12.8万',
						label: '粉丝'
					},
					{
						value: '36.9万',
						label: '获赞与收藏'
					}
				],
				panelOtherData: [{
						title: '购物',
						label: '好逛好玩又好买'
					},
					{
						title: '订单',
						label: '查看我的订单'
					},
					{
						title: '购物车',
						label: '10个商品'
					}
				],
				page: 1,
				pageSize: 10,
				status: 'loadmore',
				navBarBackground: 'red',
				titleOpacity: 0,
				scrollTop: 0,
				activeTab: 0,
				tabs: ['动态', '兴趣爱好', '个人生活照'],
				itemWidth: 0,
				activity: {},
				DynamicsLists: [],
				imgs: [],
				type: '', //mine为用户本人不展示信息
				isSelf: {},
				id: ''
			}
		},
		watch: {
			activeTab: function(val) {
				this.$refs.waterfallsFlowRef.refresh();
			}
		},
		onLoad(options) {
			if ('type' in options) this.type = options.type || '';
			if ('id' in options) {
				this.id = options.id;
				this.getSettledUserDetails(this.id);
			}
		},
		mounted() {
			this.calculateLayout()
		},
		methods: {
			/**
			@method 判断是否关注了当前用户
			**/
			async isFollow(id = '') {
				try {
					const res = await isFollow({
						userId: id
					});

					if (res.code === 200) {
						this.isSelf = {
							...res.data
						};
					}
				} catch (err) {
					//TODO handle the exception
					console.log(err);
				}
			},
			/**
			 * 智能解析中国省市区地址
			 * @param {string} address 原始地址字符串（如："山西省太原市小店区山西省"）
			 * @returns {object} 包含 province、city、district 的对象
			 */
			parseChinaAddress(address) {
				// 省级匹配规则（包含直辖市和自治区）
				const provinceRegex = /(.+?省|.+?自治区|北京市|天津市|上海市|重庆市)/;
				// 市级匹配规则（排除重复的省）
				const cityRegex = /([^省]+?市|.+?地区|.+?盟|.+?自治州)/;
				// 区级匹配规则
				const districtRegex = /([^市]+?区|[^市]+?县|.+?旗|.+?自治县)/;

				const result = {
					province: '',
					city: '',
					district: ''
				};

				// 第一步：提取省级
				const provinceMatch = address.match(provinceRegex);
				if (provinceMatch) {
					result.province = provinceMatch[1];
					address = address.replace(result.province, ''); // 移除已匹配部分
				}

				// 第二步：提取市级（自动排除省级关键词）
				const cityMatch = address.match(cityRegex);
				if (cityMatch) {
					result.city = cityMatch[1];
					address = address.replace(result.city, '');
				}

				// 第三步：提取区级
				const districtMatch = address.match(districtRegex);
				if (districtMatch) result.district = districtMatch[1];

				return result;
			},
			/**
			@method 取消关注
			@param followingId → 被关注用户的 ID（你要关注的那个人）
			**/
			async cancel() {
				try {
					const _this = this;
					const res = await unfollowUser({
						followingId: this.activity.userid,
					});

					if (res.code === 200) {
						this.$refs.uToast.show({
							type: "default",
							title: "默认主题",
							message: "取消成功！",
							iconUrl: "https://uviewui.com/demo/toast/default.png",
							complete() {

							},
						});
						this.getSettledUserDetails(this.id);
					}
				} catch (e) {
					//TODO handle the exception
					console.log(e);
				}
			},
			/**
			@method 关注用户
			@param followerId → 当前登录用户的 ID（谁在点关注按钮）
				   followingId → 被关注用户的 ID（你要关注的那个人）
			**/
			async followUser() {
				try {
					const res = await followUser({
						followingId: this.activity.userid,
					});

					if (res.code === 200) {
						this.$refs.uToast.show({
							type: "default",
							title: "默认主题",
							message: "关注成功！",
							iconUrl: "https://uviewui.com/demo/toast/default.png",
							complete() {

							},
						});
					}
				} catch (e) {
					//TODO handle the exception
					console.log(e);
				}
			},
			/**
			@method 获取搭子详情
			**/
			async getSettledUserDetails(id = '') {
				try {
					this.imgs = [];

					const res = await getSettledUserDetails({
						id: id
					});

					if (res.code === 200) {
						this.activity = {
							...res.data
						};

						for (var i = 0; i < res.data.lifePhotos.length; i++) {
							this.imgs.push({
								url: res.data.lifePhotos[i]
							});
						}

						this.getUserDynamicsLists(res.data.userid);
						this.isFollow(res.data.userid);
					}
				} catch (e) {
					//TODO handle the exception
					console.log(e);
				}
			},
			/**
			@method 通过用户id获取该用户发布过的动态
			**/
			async getUserDynamicsLists(id = '') {
				try {
					const res = await getUserDynamicsLists({
						userId: id,
						page: this.page,
						size: this.pageSize
					});

					if (res.code === 200) {
						this.DynamicsLists = [...res.data.data];

						// 判断数据数量，修改状态
						if (res.data.data.length == 0 || res.data.data.length < this.pageSize) {
							this.status = 'nomore';
							return;
						}
					}
				} catch (e) {
					//TODO handle the exception
					console.log(e);
				}
			},
			/** 
			@method 下单预约
			**/
			reservation() {
				uni.navigateTo({
					url: `/pages/order/index?id=${this.activity._id}`
				});
			},
			checkImage(e) {
				uni.previewImage({
					urls: [e.url],
				});
			},
			linkUrl(e) {
				uni.navigateTo({
					url: `/pages/index/details?id=${e._id}`
				});
				this.$refs.waterfallsFlowRef.refresh();
			},
			calculateLayout() {
				const {
					windowWidth
				} = uni.getSystemInfoSync()
				this.itemWidth = (windowWidth - 32) / 2
			},
			handleScroll(e) {
				const scrollTop = e.detail.scrollTop
				this.titleOpacity = Math.min(scrollTop / 100, 1)
				this.navBarBackground = `rgba(255,255,255,${Math.min(scrollTop / 80, 0.98)})`
			},
			switchTab(index) {
				this.activeTab = index
			}
		}
	}
</script>

<style>
	page {
		background-color: #fff;
	}
</style>
<style lang="scss" scoped>
	.container {
		width: auto;

		.item {
			padding: 10rpx 10rpx 10rpx 10rpx;

			._user {
				width: auto;
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding-top: 10rpx;

				view {
					display: flex;
					align-items: center;

					text {
						font-size: 24rpx;
						margin-left: 10rpx;
					}
				}
			}

			.title {
				color: #333;
				font-size: 30rpx;
				font-weight: 500;
				white-space: nowrap;
				/*文本强制一行显示*/
				overflow: hidden;
				/*文本溢出隐藏*/
				text-overflow: ellipsis;
				/*溢出的文本显示省略号*/
			}

			.desc {
				color: #888;
				font-size: 28rpx;
				display: -webkit-box;
				/* 必须设置，用于多行溢出 */
				-webkit-box-orient: vertical;
				/* 设置盒子排列方向为垂直 */
				-webkit-line-clamp: 2;
				/* 限制显示的行数，例如显示 3 行 */
				overflow: hidden;
				/* 隐藏超出的内容 */
			}
		}
	}

	.gradient {
		&-circle {
			border-radius: 50%;
			background: white;

			&.large {
				width: 160rpx;
				height: 160rpx;
				border: 4rpx solid #fff;
				box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
			}
		}

		&-gray {
			background: linear-gradient(45deg, #D3D3D3, #A9A9A9);
		}

		&-btn {
			background: linear-gradient(90deg, rgba(255, 255, 255, 0.9), rgba(245, 245, 245, 0.9));
		}

		&-image {
			background: linear-gradient(180deg, #1C2D41 0%, #546366 100%);
			padding-top: 133%;
			border-radius: 16rpx;
		}

		&-text {
			background: linear-gradient(90deg, #333 30%, #666 70%);
			opacity: 0.8;
		}

		&-accent {
			background: linear-gradient(90deg, #1C2D41, #546366);
		}
	}

	.flex-center {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.header {
		background: linear-gradient(180deg, #1C2D41 0%, #546366 100%);
		padding: 100rpx 30rpx 80rpx 30rpx;

		.user-info {
			display: flex;

			.avatar-box {
				position: relative;
				margin-right: 32rpx;

				.avatar-img {
					width: 160rpx;
					height: 160rpx;
					border-radius: 50%;
				}

				.upload-sign {
					font-size: 36rpx;
					line-height: 20rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					background-color: #FAE93E;
					position: absolute;
					font-weight: 600;
					right: 12rpx;
					bottom: 6rpx;
					border-radius: 50%;
					width: 40rpx;
					height: 40rpx;
				}
			}
		}

		.name-row {
			display: flex;
			align-items: center;
			margin-bottom: 10rpx;

			.username {
				color: #EFFAFB;
				font-size: 30rpx;
				font-weight: 700;
				margin-right: 16rpx;
			}
		}

		.user-id {
			color: #90A4AB;
			font-size: 24rpx;
		}

		.signature {
			color: #BCC1C4;
			font-size: 28rpx;
			padding-top: 34rpx;
		}

		.sign {
			display: flex;
			padding-top: 20rpx;

			.gender-badge {
				display: flex;
				text-align: center;
				align-items: center;
				justify-content: center;
				background-color: #707F84;
				width: 34rpx;
				height: 32rpx;
				padding: 2rpx 10rpx;
				font-size: 20rpx;
				border-radius: 40rpx;
				color: #FF8597;
				text-align: center;
				line-height: 36rpx;
			}

			.level-badge {
				padding: 5rpx 10rpx 5rpx 10rpx;
				border-radius: 32rpx;
				font-size: 24rpx;
				color: #EFFAFB;
				background-color: #637376;
				margin-right: 12rpx;
				letter-spacing: 2rpx;
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}
	}

	.data-panel {
		display: flex;
		justify-content: space-between;
		font-size: 26rpx;
		padding: 50rpx 0;
		color: #BCC1C4;

		.user-data {
			display: flex;
			justify-content: space-between;
			gap: 50rpx;

			.user-number {
				color: #EFFAFB;
				display: flex;
				justify-content: center;
				align-items: center;
			}

			.user-label {
				font-size: 22rpx;
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}

		.edit-btns {
			display: flex;

			.btn {
				padding: 0 32rpx;
				border-radius: 40rpx;
				color: #EFFAFB;
				border: 1rpx solid rgba(248, 251, 251, 0.296);
				background-color: #637376;
				display: flex;
				align-items: center;
			}
		}
	}

	.tags_flex {
		display: flex;
		align-items: center;

		/deep/ .u-tag-wrapper {
			margin-right: 15rpx;
		}
	}

	.image_flex {
		width: auto;
		display: flex;
		justify-content: space-around;
		flex-wrap: wrap;

		image {
			width: 48%;
			height: 300rpx;
			margin-bottom: 20rpx;
		}
	}

	.other-panel {
		font-size: 24rpx;
		color: #BCC1C4;
		display: flex;
		gap: 20rpx;

		.other-box {
			background-color: #637376;
			padding: 20rpx;
			border-radius: 16rpx;
			width: 200rpx;

			.other-label {
				font-size: 20rpx;
			}

			.other-title {
				color: #EFFAFB;
				padding-bottom: 6rpx;
			}
		}
	}

	/* 内容区域 */
	.content-section {
		width: auto;
		transform: translateY(-20px);
		background: white;
		border-radius: 20rpx 20rpx 0 0;
		padding: 0rpx 20rpx 0rpx 20rpx;

		.tab-bar {
			display: flex;
			padding: 0 32rpx;
			padding-bottom: 20rpx;

			.tab-item {
				flex: 1;
				text-align: center;
				padding: 24rpx 0;
				font-size: 26rpx;
				color: #666;
				position: relative;

				&.active {
					font-weight: 500;
					color: #333;
				}

				.indicator {
					position: absolute;
					bottom: 0;
					left: 50%;
					transform: translateX(-50%);
					width: 52rpx;
					height: 6rpx;
					border-radius: 18rpx;
				}
			}
		}

		.waterfall {
			padding: 16rpx;
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;

			.post-item {
				margin-bottom: 16rpx;

				.post-info {
					padding: 20rpx;

					.text-line {
						height: 32rpx;
						margin-bottom: 12rpx;
						border-radius: 8rpx;

						&.short {
							width: 60%;
						}
					}

					.stats {
						width: 40%;
						height: 24rpx;
						border-radius: 8rpx;
					}
				}
			}
		}
	}

	.add {
		width: 95%;
		position: fixed;
		left: 2.5%;
		bottom: 1.5%;
		height: 84rpx;
		background: #ffaf32;
		border: none;
		box-shadow: 0rpx 6rpx 30rpx 0rpx rgba(83, 60, 215, 0.4600);
		border-radius: 43rpx;
		font-size: 32rpx;
		color: #FFFFFF;
		line-height: 84rpx;
		text-align: center;
		letter-spacing: 2rpx;
	}
</style>